/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jard.webshop.jsfbeans;

import jard.webshop.nbp.Product;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;

/**
 *
 * @author Harteex
 */
@ManagedBean(name = "cartBacking")
@RequestScoped
public class CartBacking {
    @ManagedProperty(value = "#{cartModel}")
    private CartModel cartModel;
    
    public class CartInfoHolder {
        private Product product;
        private Integer quantity;
        private Float totalPrice;
        public CartInfoHolder() {
            //
        }

        public Product getProduct() {
            return product;
        }

        public void setProduct(Product product) {
            this.product = product;
        }

        public Integer getQuantity() {
            return quantity;
        }

        public void setQuantity(Integer quantity) {
            this.quantity = quantity;
        }

        public Float getTotalPrice() {
            return totalPrice;
        }

        public void setTotalPrice(Float totalPrice) {
            this.totalPrice = totalPrice;
        }
    }
    
    private List<CartInfoHolder> products;

    /** Creates a new instance of CartBacking */
    public CartBacking() {
        //
    }

    public CartModel getCartModel() {
        return cartModel;
    }

    public void setCartModel(CartModel cartModel) {
        this.cartModel = cartModel;
    }

    public List<CartInfoHolder> getProducts() {
        if (products == null) {
            products = new ArrayList<CartInfoHolder>();
            
            System.out.println("cartModel = " + cartModel == null ? "null" : "not null! :D");

            if (cartModel != null && cartModel.getProducts() != null) {
                for (Entry<Product, Integer> pair : cartModel.getProducts().entrySet()) {
                    CartInfoHolder cih = new CartInfoHolder();
                    cih.setProduct(pair.getKey());
                    cih.setQuantity(pair.getValue());
                    cih.setTotalPrice(pair.getKey().getPrice() * pair.getValue()); // Price * Quantity
                    products.add(cih);
                    System.out.println("copying product...");
                }
            }
        }
        
        return products;
    }

    public void setProducts(List<CartInfoHolder> products) {
        this.products = products;
    }
}
